﻿using System;
using System.Collections.Generic;
using System.Linq;
using PBOffice.DAL;
using System.Data.Objects;

namespace PBOffice.BLL
{
	#region 业务逻辑层消息实体类
	/// <summary>
	/// 业务逻辑层消息实体类
	/// </summary>
	public class MessageBLL
	{
		public int MessNo { get; set; }
		public string MessTitle { get; set; }
		public string MessageTypeId { get; set; }
		public string MessContent { get; set; }
		public string sender { get; set; }
		public string receiver { get; set; }
		public DateTime? MessStartTime { get; set; }
		public DateTime? MessEndTime { get; set; }
		public DateTime? MessCreateTime { get; set; }
		public bool IsPublish { get; set; }
	} 
	#endregion

	#region 消息模块业务类
	/// <summary>
	/// 消息模块业务类
	/// </summary>
	public class MsgMngBLL:IDisposable
	{
		MyOfficeEntities db = new MyOfficeEntities();
		#region 增
		public void AddNewMessage(string title, string content, bool isCommon, int typeNO, DateTime start, DateTime end, int userNO, List<int> sendto)
		{
			var msg = Message.CreateMessage(0, title, content, false, isCommon);
			msg.MessageType = db.MessageTypes.Single(mt => mt.MessageTypeNo == typeNO);
			msg.User = db.Users.SingleOrDefault(u => u.UserNo == userNO);
			msg.MessStartTime = start;
			msg.MessEndTime = end;
			msg.MessCreateTime = DateTime.Now;
			db.Messages.AddObject(msg);
			db.SaveChanges();
			if (sendto == null) return;
			foreach (var item in sendto)
			{
				var stu = SendToUser.CreateSendToUser(msg.MessNo, item, false);
				db.SendToUsers.AddObject(stu);
			}
			db.SaveChanges();
		}
		#endregion

		#region 删

		public void DeleteMess(int id)
		{
			var msg = (from m in db.Messages
					   where m.MessNo == id
					   select m).SingleOrDefault();
			if (msg != null)
			{
				var stus = from s in db.SendToUsers
						   where s.MessNo == id
						   select s;
				foreach (var stu in stus)
					db.SendToUsers.DeleteObject(stu);
				db.Messages.DeleteObject(msg);
				db.SaveChanges();
			}
		}

		#endregion

		#region 改
		/// <summary>
		/// 短信已读！
		/// </summary>
		/// <param name="userNO"></param>
		/// <param name="messNO"></param>
		public void SetMessageRead(int userNO, int messNO)
		{
			var s = db.SendToUsers.SingleOrDefault(stu => stu.UserNo == userNO && stu.MessNo == messNO);
			if (s == null)//记录不存在 
			{
				var msg = db.Messages.SingleOrDefault(m => m.MessNo == messNO);
				if (msg != null && msg.IsCommon) //存在记录，且为群发
				{
					var stu=SendToUser.CreateSendToUser(messNO, userNO, true);
					db.SendToUsers.AddObject(stu);
					db.SaveChanges();
				}
			}
			else
			{
				s.Readed = true;
				db.SaveChanges();
			}
		}

		/// <summary>
		/// 更新消息
		/// </summary>
		/// <param name="id"></param>
		/// <param name="title"></param>
		/// <param name="content"></param>
		/// <param name="isCommon"></param>
		/// <param name="typeNO"></param>
		/// <param name="start"></param>
		/// <param name="end"></param>
		/// <param name="userNO"></param>
		/// <param name="sendto"></param>
		public void UpdateMess(int id, string title, string content, bool isCommon, int typeNO, DateTime start, DateTime end, List<int> sendto)
		{
			var msg = GetMessage(id);
			msg.MessTitle = title;
			msg.MessContent = content;
			msg.IsCommon = isCommon;
			msg.MessageType = db.MessageTypes.Single(mt => mt.MessageTypeNo == typeNO);
			msg.MessStartTime = start;
			msg.MessEndTime = end;
			db.SaveChanges();
			if (sendto == null) return;
			foreach (var item in
				from stu in db.SendToUsers
				where stu.MessNo == msg.MessNo
				select stu)
				db.SendToUsers.DeleteObject(item);
			db.SaveChanges();
			foreach (var item in sendto)
			{
				var stu = SendToUser.CreateSendToUser(msg.MessNo, item, false);
				db.SendToUsers.AddObject(stu);
			}
			db.SaveChanges();
		}

		/// <summary>
		/// 更新消息发布状态
		/// </summary>
		/// <param name="id"></param>
		public void ChangePublishState(int id)
		{
			var message = (from m in db.Messages
						   where m.MessNo == id
						   select m).SingleOrDefault();
			message.MessCreateTime = DateTime.Now;
			message.IsPublish = !message.IsPublish;
			db.SaveChanges();
		}
		#endregion

		#region 查

		#region 获取用户资料

		/// <summary>
		/// 获取经过部门、用户id、用户名过滤的所有用户
		/// </summary>
		/// <param name="departNo"></param>
		/// <param name="userId"></param>
		/// <param name="username"></param>
		/// <returns></returns>
		public List<User> GetFilterUsers(int? departNo, string userId, string username)
		{
			var sql = string.Empty;
			if (departNo != null)
				sql = "and user.Department.DepNo=@depno ";
			else
				departNo = 0;
			if (!string.IsNullOrEmpty(userId))
				sql += "and user.UserId=@userid";
			else
				userId = string.Empty;
			username = username ?? string.Empty;
			sql = "select VALUE user from MyOfficeEntities.Users as user where user.UserName like @username " + sql;
			var users = db.CreateQuery<User>(sql, new ObjectParameter[] { new ObjectParameter("depno", departNo), new ObjectParameter("userid", userId), new ObjectParameter("username", "%" + username + "%") });
			return users.ToList();
		}

		/// <summary>
		/// 获取所有收信人信息
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public List<MessageBLL> GetReceiverNames(int id)
		{
			var mbs = new List<MessageBLL>();
			var msg = db.Messages.SingleOrDefault(m => m.MessNo == id);
			if (msg != null)
			{
				if (msg.IsCommon)
					mbs.Add(new MessageBLL() { receiver = "所有人" });
				else
				{
					foreach (var stu in db.SendToUsers.Where(stu => stu.MessNo == msg.MessNo))
					{
						var mb = new MessageBLL();
						mb.receiver = stu.User.UserName;
						mbs.Add(mb);
					}
				}
			}
			return mbs;
		}
		#endregion

		/// <summary>
		/// 根据类型id返回类型名称
		/// </summary>
		/// <param name="typeNO"></param>
		/// <returns></returns>
		public string GetMessageTypeName(int typeNO)
		{
			return db.MessageTypes.Single(mt => mt.MessageTypeNo == typeNO).MessageTypeId;
		}
		/// <summary>
		/// 返回指定id的消息
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public Message GetMessage(int id)
		{
			var msg= (from m in db.Messages
					where m.MessNo == id
					select m).SingleOrDefault();
			return msg;
		}

		/// <summary>
		/// 获取所有消息接收者
		/// </summary>
		/// <param name="messNO"></param>
		/// <returns></returns>
		public List<User> GetReceivers(int messNO)
		{
			var users = from stu in db.SendToUsers
						where stu.MessNo == messNO
						join user in db.Users on stu.User equals user
						select user;
			return users.ToList();
		}

		/// <summary>
		/// 短信已读？
		/// </summary>
		/// <param name="userNO"></param>
		/// <param name="messNO"></param>
		/// <returns></returns>
		public bool IsMessageRead(int userNO, int messNO)
		{
			var s = db.SendToUsers.SingleOrDefault(stu => stu.UserNo == userNO && stu.MessNo == messNO);
			return s == null ? false : s.Readed;
		}
	
		/// <summary>
		/// 获取指定用户发送的所有信息
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		public List<MessageBLL> GetSentMessages(User user)
		{
			return GetAllMessages(DateTime.MinValue, DateTime.MaxValue, user, false).Where(mb => mb.IsPublish).ToList();
		}

		public List<up_received_messages_Result> GetReceivedMessages(User user)
		{
			return db.up_received_messages(user.UserNo).OrderByDescending(m=>m.MessNo).ToList();
		}

		/// <summary>
		/// 根据日期获取所有需要管理的消息
		/// </summary>
		/// <param name="start">起始日期</param>
		/// <param name="end">截至日期</param>
		/// <param name="user">与要查询消息相关联的用户，如果为null则查找所有消息(管理员)</param>
		/// <returns></returns>
		public List<MessageBLL> GetAllMessages(DateTime start, DateTime end, User user, bool getAll)
		{
			List<MessageBLL> msgs = new List<MessageBLL>();

			start = start.Date;
			end = end.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
			foreach (var msg in db.Messages.OrderByDescending(m => m.MessNo))
			{
				if (!(getAll || msg.IsCommon || msg.User.UserNo == user.UserNo)) continue; ;//权限管理，管理员可以查看所有消息、本人可以查看自己发的消息。

				if (msg.User.UserNo != user.UserNo && !msg.IsPublish) continue;//如果不是本人且该消息未发布，不能查看该消息。
				if (msg.MessStartTime < start || msg.MessEndTime > end) continue;//是否符合时间要求
				MessageBLL mb = new MessageBLL();
				if (msg.IsCommon)//所有人的记录
					mb.receiver = "所有人";
				else
					mb.receiver = "查看详单";
				mb.MessTitle = msg.MessTitle;
				mb.MessageTypeId = msg.MessageType.MessageTypeId;
				mb.MessContent = msg.MessContent;
				mb.sender = msg.User.UserName;
				mb.MessStartTime = msg.MessStartTime;
				mb.MessEndTime = msg.MessEndTime;
				mb.MessCreateTime = msg.MessCreateTime;
				mb.IsPublish = msg.IsPublish;
				mb.MessNo = msg.MessNo;
				msgs.Add(mb);
			}
			return msgs;
		}

		/// <summary>
		/// 获取指定消息的内容
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public MessageBLL GetTitleContent(int id)
		{
			var mb = new MessageBLL();
			var msg = (from m in db.Messages
					   where m.MessNo == id
					   select m).SingleOrDefault();
			if (msg != null)
			{
				mb.MessTitle = msg.MessTitle;
				mb.MessContent = msg.MessContent;
			}
			return mb;
		}

		#endregion

		///<summary>
		///释放资源
		///</summary>
		public void Dispose()
		{
			db.Dispose();
		}
	} 
	#endregion
}
